Just like with HTML, CSS and even regular JavaScript, you can write jQuery in any kind of editor, even Windows Notepad. However, using a simple text editor like Notepad for creating webpages is like using a screwdriver to drill holes into a piece of wood: It works, but it takes a lot longer and is way less pleasant.
If you already have an HTML editor that allows you to work easily with JavaScript, then it will likely be good for writing jQuery as well, but there are editors out there that will treat jQuery as a first-class citizen and help you type it faster and more efficient.
I personally use TSW WebCoder, which has a bunch of awesome IntelliSense features to aid you, covering all the technologies you need: HTML, CSS, JavaScript, PHP and of course jQuery. Having a list of possible properties, methods and their parameters is a huge help, especially when you're brand new to jQuery. If your current editor already does all of this, and you feel comfortable with it, then by all means stick to it - if not, then consider giving WebCoder a try.
> More information about TSW WebCoderHere's a couple of screenshots to show you why TSW WebCoder makes it a lot easier to work with jQuery:
TSW WebCoder showing possible methods on a jQuery object<script type="text/javascript" src="jquery-1.5.1.js"></script>A part of your page should now look something like this:
<head> <title>jQuery test</title> <script type="text/javascript" src="jquery-1.5.1.js"></script> </head>A more modern approach, instead of downloading and hosting jQuery yourself, is to include it from a CDN (Content Delivery Network). Both Google and Microsoft host several different versions of jQuery and other JavaScript frameworks. It saves you from having to download and store the jQuery framework, but it has a much bigger advantage: Because the file comes from a common URL that other websites may use as well, chances are that when people reaches your website and their browser requests the jQuery framework, it may already be in the cache, because another website is using the exact same version and file. Besides that, most CDN's will make sure that once a user requests a file from it, it's served from the server closest to them, so your European users won't have to get the file all the way from the US and so on.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>I suggest that you use this approach, unless you have a specific reason for hosting jQuery yourself. Here is a link to the jQuery CDN information from Google:
<div id="divTest1"></div> <script type="text/javascript"> $("#divTest1").text("Hello, world!"); </script>Okay, so we have a div tag with the id of "divTest1". In the JavaScript code we use the $ shortcut to access jQuery, then we select all elements with an id of "divTest1" (there is just one though) and set its text to "Hello, world!". You may not know enough about jQuery to understand why and how this works, but as you progress through this tutorial, all of the elements will be explained in detail.
<div id="divTest2"></div> <script type="text/javascript"> document.getElementById("divTest2").innerHTML = "Hello, world!"; </script>And it would be even longer if our HTML element didn't have an ID, but for instance just a class.
<div id="divTest1"></div> <script type="text/javascript"> function DocumentReady() { $("#divTest1").text("Hello, world!"); } $(document).ready(DocumentReady); </script>What we do here is that we create a function, called DocumentReady, which should be fired as soon as the document is ready for DOM manipulation. In the last line, we use the ready() method to assign our function to the ready event, to tell jQuery that as soon as the document is ready, we want it to call our function.
<div id="divTest2"></div> <script type="text/javascript"> $(document).ready(function() { $("#divTest2").text("Hello, world!"); }); </script>But of course, this wasn't even short enough for the jQuery team, so they decided to create a version (overload) of the jQuery constructor which takes a ready function as a parameter, to make it even shorter:
<div id="divTest3"></div> <script type="text/javascript"> $(function() { $("#divTest3").text("Hello, world!"); }); </script>In the last example, our anonymous function is passed directly to the jQuery constructor, which assigns it to the ready event. As you will see when you test the code, the event is fired as soon as the page is loaded, most of the time so fast that you won't even realize it.
<div id="divTest1"></div> <script type="text/javascript"> $("#divTest1").text("Hello, world!").css("color", "blue"); </script>It works like this: We instantiate a new jQuery object and select the divTest1 element with the $ character, which is a shortcut for the jQuery class. In return, we get a jQuery object, allowing us to manipulate the selected element. We use that object to call the text() method, which sets the text of the selected element(s). This method returns the jQuery object again, allowing us to use another method call directly on the return value, which is the css() method.
<div id="divTest2"></div> <script type="text/javascript"> $("#divTest2").text("Hello, world!") .removeClass("blue") .addClass("bold") .css("color", "blue"); </script>JavaScript will simply throw away the extra whitespace when interpreting the code and execute it as one long line of code with several method calls.
$("#divTest")An example of it in use:
<div id="divTest"></div> <script type="text/javascript"> $(function() { $("#divTest").text("Test"); }); </script>Now, while there is only a single element that matches our query above, you should be aware that the result is a list, meaning that it can contain more than one element, if the query matches more than one. A common example of this is to match all elements which uses one or several CSS classes.
<ul> <li class="bold">Test 1</li> <li>Test 2</li> <li class="bold">Test 3</li> </ul> <script type="text/javascript"> $(function() { $(".bold").css("font-weight", "bold"); }); </script>
$("span.bold").css("font-weight", "bold");This will match all span elements with "bold" as the class. Of course, it can be used with ID's and pretty much all of the other selectors as well.
<span title="Title 1">Test 1</span><br /> <span>Test 2</span><br /> <span title="Title 3">Test 3</span><br /> <script type="text/javascript"> $(function() { $("[title]").css("text-decoration", "underline"); }); </script>We use the attribute selector to find all elements on the page which has a title attribute and then underline it. As mentioned, this will match elements with a title element no matter what their value is, but sometimes you will want to find elements with a specific attribute which has a specific value.
<a href="http://www.google.com" target="_blank">Link 1</a><br /> <a href="http://www.google.com" target="_self">Link 2</a><br /> <a href="http://www.google.com" target="_blank">Link 3</a><br /> <script type="text/javascript"> $(function() { $("a[target='_blank']").append(" [new window]"); }); </script>The selector simply tells jQuery to find all links (the a elements) which has a target attribute that equals the string value "_blank" and then append the text "[new window]" to them. But what if you're looking for all elements which don't have the value? Inverting the selector is very easy:
$("a[target!='_blank']").append(" [same window]");The difference is the != instead of =, a common way of negating an operator within many programming languages.
$("input[name^='txt']").css("color", "blue");Find elements with a value which ends with a specific string using the $= operator:
$("input[name$='letter']").css("color", "red");Find elements with a value which contains a specific word:
$("input[name*='txt']").css("color", "blue");
<div id="divTestArea1"> <b>Bold text</b> <i>Italic text</i> <div id="divTestArea2"> <b>Bold text 2</b> <i>Italic text 2</i> <div> <b>Bold text 3</b> </div> </div> </div> <script type="text/javascript"> $("#divTestArea1 > b").css("color", "blue"); </script>As you will see, only the first bold tag is colored. Now, if you had used the second approach, both bold tags would have been colored blue. Try the following example, where the only thing changed is the greater-than character which has been replaced with a space, to note that we also accept non-direct descendants or "grand children" as they are sometimes called:
<div id="divTestArea1"> <b>Bold text</b> <i>Italic text</i> <div id="divTestArea2"> <b>Bold text 2</b> <i>Italic text 2</i> <div> <b>Bold text 3</b> </div> </div> </div> <script type="text/javascript"> $("#divTestArea1 b").css("color", "blue"); </script>Now the cool thing is that you can actually go back up the hierarchy if needed, using the parent() method. We'll look into that in another chapter of this tutorial.
<div id="divTestArea1" style="padding: 50px; background-color: #89BC38; text-align: center; display: none;"> <b>Hello, world!</b> </div> <a href="javascript:void(0);" onclick="ShowBox();">Show box</a> <script type="text/javascript"> function ShowBox() { $("#divTestArea1").fadeIn(); } </script>You can fade a lot of different elements, like divs, spans or links. The fadeIn() method can take up to three parameters. The first one allows you to specify the duration of the effect in milliseconds, or "fast" or "slow", which is the same as specifying either 200 or 600 milliseconds. Here's an example of it in use:
<div id="divTestArea21" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div> <div id="divTestArea22" style="width: 50px; height: 50px; display: none; background-color: #C3D1DF;"></div> <div id="divTestArea23" style="width: 50px; height: 50px; display: none; background-color: #9966FF;"></div> <a href="javascript:void(0);" onclick="ShowBoxes();">Show boxes</a> <script type="text/javascript"> function ShowBoxes() { $("#divTestArea21").fadeIn("fast"); $("#divTestArea22").fadeIn("slow"); $("#divTestArea23").fadeIn(2000); } </script>Don't mind all the HTML, it's just there so that you can see the difference between the fading durations. Now, the second parameter can either be the name of an easing function (which we won't use in this tutorial) or a callback function that you may supply, to be called once the effect is done. Here's an example of that, combined with the use of the fadeOut() method, which obviously has the reverse effect of fadeIn():
<div id="divTestArea3" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div> <script type="text/javascript"> $(function() { $("#divTestArea3").fadeIn(2000, function() { $("#divTestArea3").fadeOut(3000); }); }); </script>There may be situations where you want to fade an element in our out depending on its current state. You could of course check if it is visible or not and then call either fadeIn() or fadeOut(), but the nice jQuery developers have supplied us with a specific method for toggling an element, called fadeToggle(). It takes the same parameters as fadeIn() and fadeOut(), so it's very easy to use. Here's a little example:
<div id="divTestArea4" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div><br /> <a href="javascript:void(0);" onclick="ToggleBox();">Toggle box</a> <script type="text/javascript"> function ToggleBox() { $("#divTestArea4").fadeToggle("slow"); } </script>And that's how easy it is to use the fading effects of jQuery.
<div id="divTestArea1" style="padding: 50px; background-color: #89BC38; text-align: center; display: none;"> <b>Hello, world!</b> </div> <a href="javascript:void(0);" onclick="ShowBox();">Show box</a> <script type="text/javascript"> function ShowBox() { $("#divTestArea1").slideDown(); } </script>For hiding the box again, we can use the slideUp() method. They both take the same set of parameters, which are all optional. The first parameter allows you to specify a duration for the effect in milliseconds, or "fast" or "slow", which is the same as specifying either 200 or 600 milliseconds.Let's try an example where we do just that:
<div id="divTestArea21" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div> <div id="divTestArea22" style="width: 50px; height: 50px; display: none; background-color: #C3D1DF;"></div> <div id="divTestArea23" style="width: 50px; height: 50px; display: none; background-color: #9966FF;"></div> <a href="javascript:void(0);" onclick="ShowBoxes();">Show boxes</a> <script type="text/javascript"> function ShowBoxes() { $("#divTestArea21").slideDown("fast"); $("#divTestArea22").slideDown("slow"); $("#divTestArea23").slideDown(2000); } </script>There's a bit more HTML than usual, but that's only there for you to be able to see the different paces in which the boxes are shown. Notice how the first box is there almost instantly, the second box is pretty close and the third box is slower, because it uses a full two seconds to slide down.
<div id="divTestArea3" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div> <script type="text/javascript"> $(function() { $("#divTestArea3").slideDown(2000, function() { $("#divTestArea3").slideUp(3000); }); }); </script>The ability to do this can be very useful for combining several effects, as you can see. In this example, the callback function we supply will be called as soon as the slideDown() method is completely finished and then the slideUp() method is called.
<div id="divTestArea4" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div><br /> <a href="javascript:void(0);" onclick="ToggleBox();">Toggle box</a> <script type="text/javascript"> function ToggleBox() { $("#divTestArea4").slideToggle("slow"); } </script>
<div style="height: 60px;"> <div id="divTestBox1" style="height: 50px; width: 50px; background-color: #89BC38; position: absolute;"></div> </div> <script type="text/javascript"> $(function() { $("#divTestBox1").animate( { "left" : "200px" } ); }); </script>The first, and only required, parameter of the animate function is a map of the CSS properties that you wish to have altered. In this case, we have an absolutely positioned div element, which we tell jQuery to move until it has reached a left property of 200 pixels.
<div style="height: 60px;"> <div id="divTestBox2" style="height: 50px; width: 50px; background-color: #89BC38; position: absolute;"></div> </div> <script type="text/javascript"> $(function() { $("#divTestBox2").animate( { "left" : "200px" }, 5000 ); }); </script>As the third parameter, we can specify a callback function to be called once the animation is done. This can be very useful for performing a number of different animations in a row. For instance, check out this example:
<div style="height: 40px;"> <div id="divTestBox3" style="height: 20px; width: 20px; background-color: #89BC38; position: absolute;"></div> </div> <script type="text/javascript"> $(function() { $("#divTestBox3").animate( { "left" : "100px" }, 1000, function() { $(this).animate( { "left" : "20px" }, 500, function() { $(this).animate({ "left" : "50px" }, 500); } ) } ); }); </script>It might seem a bit overwhelming, but what we do is that we call the animate method and ask for the left property of our test "div" to be animated until it reaches a left of 100 pixels. We want it to take 1 second (1000 milliseconds) and once it completes, we wish for a new animation to start, which moves it back to 20 pixels within half a second, and as soon as THAT animation is done, we move it a bit right again, so that it now has a left property of 50 pixels.
<div style="height: 40px;"> <div id="divTestBox4" style="height: 20px; width: 20px; background-color: #89BC38; position: absolute;"></div> </div> <script type="text/javascript"> $(function() { $("#divTestBox4").animate({ "left" : "100px" }, 1000); $("#divTestBox4").animate({ "left" : "20px" }, 500); $("#divTestBox4").animate({ "left" : "50px" }, 500); }); </script>
<a href="javascript:void(0);" onclick="$('#divTestArea1').slideDown(5000);">Show box</a> <a href="javascript:void(0);" onclick="$('#divTestArea1').stop();">Stop</a> <div id="divTestArea1" style="padding: 100px; background-color: #89BC38; text-align: center; display: none;"> <b>Hello, world!</b> </div>To make the example a bit more compact, I have used inline calls in the onclick events of the two links. When you click the first link, the slideDown() method is used on our div element, starting a slow slide down. A click on the second link will kill the current animation being performed on the selected element. This is the default behavior of the stop() method, but two optional parameters allows us to do things differently. The first parameter specifies whether the animation queue should be cleared or not. The default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards. The following example will demonstrate that:
<a href="javascript:void(0);" onclick="$('#divTestArea2').slideDown(5000).slideUp(5000);">Show box</a> <a href="javascript:void(0);" onclick="$('#divTestArea2').stop();">Stop</a> <a href="javascript:void(0);" onclick="$('#divTestArea2').stop(true);">Stop all</a> <a href="javascript:void(0);" onclick="$('#divTestArea2').clearQueue().hide();">Reset</a> <div id="divTestArea2" style="padding: 100px; background-color: #89BC38; text-align: center; display: none;"> <b>Hello, world!</b> </div>We have added a second animation to the "Show box" link. This will slowly slide down the box, and once done, slide it up again. The queue system makes sure that these steps are performed in sequence. Now, click the "Reset" link to have the box hidden again and then click the "Show box" link once more, followed by a click on "Stop". You will see that the first animation is stopped, allowing for the second animation to be executed. However, if you try again and click on the "Stop all" instead, the true value passed will make sure that the entire queue is cleared and that all animation on the element is stopped.
<a href="javascript:void(0);" onclick="$('#divTestArea3').slideDown(5000);">Show box</a> <a href="javascript:void(0);" onclick="$('#divTestArea3').stop(true);">Stop</a> <a href="javascript:void(0);" onclick="$('#divTestArea3').stop(true, true);">Stop but finish</a> <a href="javascript:void(0);" onclick="$('#divTestArea3').clearQueue().hide();">Reset</a> <div id="divTestArea3" style="padding: 100px; background-color: #89BC38; text-align: center; display: none;"> <b>Hello, world!</b> </div>Try the two "Stop" variations - the first will stop immediately, while the second one will rush the animation to finish.
<div id="divTest"> <b>Test</b> <input type="text" id="txtTest" name="txtTest" value="Input field" /> </div> <script type="text/javascript"> $(function() { alert("Text: " + $("#divTest").text()); alert("HTML: " + $("#divTest").html()); alert("Value: " + $("#divTest").val()); alert("Text: " + $("#txtTest").text()); alert("HTML: " + $("#txtTest").html()); alert("Value: " + $("#txtTest").val()); }); </script>So a call to one of these methods with no parameters will simply return the desired property. If we want to set the property instead, we simply specify an extra parameter. Here's a complete example:
<div id="divText"></div> <div id="divHtml"></div> <input type="text" id="txtTest" name="txtTest" value="Input field" /> <script type="text/javascript"> $(function() { $("#divText").text("A dynamically set text"); $("#divHtml").html("<b><i>A dynamically set HTML string</i></b>"); $("#txtTest").val("A dynamically set value"); }); </script>And that's how easy it is to set text, HTML and values.
<p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> <script type="text/javascript"> $(function() { $("p").text(function(index, oldText) { return "Existing text: " + oldText + ". New text: A dynamically set text (#" + index + ")"; }); }); </script>We start out with three similar paragraph elements, which text is their only difference. In the jQuery code, we select all of them and then use the special version of the text() method to replace their current text with a newly constructed text, based on the two parameters that jQuery provides for us: The index of the current element as well as its current text. This new text is then returned to jQuery, which will replace the current text with the new one.
<a href="http://www.google.com" id="aGoogle1">Google Link</a> <script type="text/javascript"> $(function() { alert($("#aGoogle1").attr("href")); }); </script>In this example, we get the value of the "href" attribute of our link and then show it to the user. To change an attribute, we simply specify an extra parameter:
<a href="http://www.google.com" id="aGoogle2">Google Link</a> <script type="text/javascript"> $(function() { $("#aGoogle2").attr("href", "http://www.google.co.uk"); }); </script>This will change the link to point to the British version of Google. The attr() method can also take a map of name/value pairs, for setting multiple attributes at the same time. Here we set both the href and the title attributes simultaneously:
<a href="http://www.google.com" id="aGoogle3">Google Link</a> <script type="text/javascript"> $(function() { $("#aGoogle3").attr( { "href" : "http://www.google.co.uk", "title" : "Google.co.uk" }); }); </script>The attr() method also supports the special overload where the value parameter is instead a callback function, allowing you to access the index of the element selected as well as the existing attribute value. Here's an example of just that:
<a href="http://www.google.com/" class="google">Google.com</a><br /> <a href="http://www.google.co.uk/" class="google">Google UK</a><br /> <a href="http://www.google.de/" class="google">Google DE</a><br /> <script type="text/javascript"> $(function() { $("a.google").attr("href", function(index, oldValue) { return oldValue + "imghp?tab=wi"; }); }); </script>We simply change all the Google links to point to the Image search instead of the default page, by adding an extra parameter to the href attribute. In this example we don't really use the index parameter, but we could have if we needed it, to tell us which index in the list of elements selected we're currently dealing with.
.bold { font-weight: bold; } .blue { color: blue; }In the following example we will use three of the most interesting class related methods: hasClass(), which checks if one or several elements already has a specific class defined, addClass(), which simply adds a class name to one or several elements and the removeClass() methods, which will.... well, you've probably already guessed it.
<a href="javascript:void(0);" onclick="ToggleClass(this);">Toggle class</a> <script type="text/javascript"> function ToggleClass(sender) { if($(sender).hasClass("bold")) $(sender).removeClass("bold"); else $(sender).addClass("bold"); } </script>The example is actually very simple. When the link is clicked, we send the link itself (this) as a parameter to the ToggleClass() method that we have defined. In it, we check if the sender already has the "bold" class - if it has, we remove it, otherwise we add it. This is a pretty common thing to do, so obviously the jQuery people didn't want us to write an entire three lines of code to it. That's why they implemented the toggleClass() method, with which we can turn our entire example above into a single line of code:
<a href="javascript:void(0);" onclick="$(this).toggleClass('bold');">Toggle class</a>Of course, we can select multiple elements, where we can add or remove multiple classes, as well. Here's an example of just that:
<div id="divTestArea1"> <span>Test 1</span><br /> <div>Test 2</div> <b>Test 3</b><br /> </div> <script type="text/javascript"> $(function() { $("#divTestArea1 span, #divTestArea1 b").addClass("blue"); $("#divTestArea1 div").addClass("bold blue"); }); </script>First we select the span and the b tag, which we add a single class to: the bold class. Then we select the div tag, which we add two classes to, separated by a space: The bold and the blue class. The removeClass() methods works just the same way, allowing you to specify several classes to be removed, separated with a space.
<a href="javascript:void(0);" onclick="$('#olTestList1').append('<li>Appended item</li>');">Append</a> <a href="javascript:void(0);" onclick="$('#olTestList1').prepend('<li>Prepended item</li>');">Prepend</a> <ol id="olTestList1"> <li>Existing item</li> <li>Existing item</li> </ol>We have to links: The first will append an item to the list, meaning that the new item will be inserted as the last item. The other link will prepend a link to the list, which means that the new item will be inserted as the first item of the list. In this example, we simply insert a piece of HTML, but we could have generated the new items with jQuery as well, or created it through regular JavaScript code and DOM elements. In fact, both the append() and the prepend() method takes an infinite amount of new elements as parameters. In the next example, we will demonstrate this as well as the ability to add elements in various forms:
<a href="javascript:void(0);" onclick="AppendItemsToList();">Append items</a> <ol id="olTestList2"></ol> <script type="text/javascript"> function AppendItemsToList() { var item1 = $("<li></li>").text("Item 1"); var item2 = "<li>Item 2</li>"; var item3 = document.createElement("li"); item3.innerHTML = "Item 3"; $("#olTestList2").append(item1, item2, item3); } </script>As you can see, item1 is a jQuery generated element, item2 is a simple HTML string and item3 is a JavaScript DOM generated element. They are all appended to the list using the same call and of course this would have worked for the prepend() method too.
<a href="javascript:void(0);" onclick="PrependItemsToList();">Prepend items</a> <ol id="olTestList3"></ol> <script type="text/javascript"> function PrependItemsToList() { $("#olTestList3").prepend($("<li></li>").text("prepend() item")); $("<li></li>").text("prependTo() item").prependTo("#olTestList3"); } </script>In this example, we prepend the items, but you could of course do the exact same using append() and appendTo(). As you can see, the result is the same - only the order of what we do differs.
<a href="javascript:void(0);" onclick="$('input.test1').before('<i>Before</i>');">Before</a> <a href="javascript:void(0);" onclick="$('input.test1').after('<b>After</b>');">After</a> <br /><br /> <input type="text" class="test1" value="Input 1" name="txtInput1" /><br /> <input type="text" class="test1" value="Input 2" name="txtInput2" /><br />Depending on which of the two links you click, an italic or a bold tag will be inserted before or after each input element on the page using the "test1" class. Just like with append() and prepend(), both after() and before() allows you to use HTML strings, DOM elements and jQuery objects as parameters and an infinite amount of them as well. We'll demonstrate that in the next example:
<a href="javascript:void(0);" onclick="InsertElements();">Insert elements</a> <br /><br /> <span id="spnTest2">Hello world? </span> <script type="text/javascript"> function InsertElements() { var element1 = $("<b></b>").text("Hello "); var element2 = "<i>there </i>"; var element3 = document.createElement("u"); element3.innerHTML = "jQuery!"; $("#spnTest2").after(element1, element2, element3); } </script>In this example, we create a jQuery object, an HTML string and a JavaScript DOM element, and then we use the after() method to insert all of them after our span tag. Of course, the before() method could have been used in exactly the same way.
<a href="javascript:void(0);" onclick="InsertElementsBefore();">Insert elemenets</a> <br /><br /> <span id="spnTest3">Hello world? </span> <script type="text/javascript"> function InsertElementsBefore() { $("#spnTest3").before($("<i></i>").text("before() ")); $("<b></b>").text("insertBefore() ").insertBefore("#spnTest3"); } </script>In this example, we insert the items before the span tag, but you could of course do the exact same using after() and insertAfter(), if you wish to insert after the target elemenet. As you can see, the result is the same - only the order of what we do differs.
<a href="javascript:void(0);" onclick="$('#divTestArea1').empty();">empty() div</a> <a href="javascript:void(0);" onclick="$('#divTestArea1').remove();">remove() div</a> <div id="divTestArea1" style="height: 100px; width: 300px; padding: 20px; border: 1px solid silver; background-color: #eee;"> <b>Bold text</b> <i>Italic text</i> </div>The first link will call the empty() method on our test div, removing all the child elements. The second link will remove the entire div, including any child elements. Pretty simple stuff.
<a href="javascript:void(0);" onclick="$('#divTestArea2 b').remove('.more');">remove() more bold</a> <div id="divTestArea2" style="height: 100px; width: 300px; padding: 20px; border: 1px solid silver; background-color: #eee;"> <b>Bold text</b><br /> <b class="more">More bold text</b><br /> <b class="more">Even more bold text</b><br /> </div>We start out by selecting all bold tags inside our test div. We then call the remove() method on the selected elements, and pass in the .more filter, which will make sure that we only get elements which uses the class "more". As a result, only the last two bold texts are removed.
<a href="javascript:void(0);" onclick="alert('Hello, world!');">Test</a>And of course this is still perfectly valid when using jQuery. However, using jQuery, you can bind code to the event of an element even easier, especially in cases where you want to attach anonymous functions or use the same code for multiple events, or even the same code for multiple events of multiple elements. As an example, you could bind the same event to all links and span tags in your document, with only a few lines of code like this:
<script type="text/javascript"> $(function() { $("a, span").bind("click", function() { alert('Hello, world!'); }); }); </script>We use the bind method, which is essential when working with events and jQuery. In the following chapters we will tell you more about how it works, along with other event related information you need.
<a href="javascript:void(0);">Test 1</a> <a href="javascript:void(0);">Test 2</a> <script type="text/javascript"> $(function() { $("a").bind("click", function() { alert($(this).text()); }); }); </script>It works by selecting all links (<a> elements) and then bind the anonymous function you see to the click event. A cool little feature is that jQuery will automatically assign the element that is clicked, to the "this" keyword inside of the anonymous function. This will allow you to access the element that activates the element, even when you assign the same code to multiple elements.
<div id="divArea" style="background-color: silver; width: 100px; height: 100px;"> </div> <script type="text/javascript"> $("#divArea").bind("mousemove", function(event) { $(this).text(event.pageX + "," + event.pageY); }); </script>We create a div element of a reasonable size and a background color. For this div, we subscribe to the mousemove event, with an anonymous function with a parameter called "event". This object gives us access to the pageX and pageY properties, which tells us where on the page the mouse cursor currently is, relative to the top left corner of the document. Try the example and move the cursor over the div element and you will see the coordinates updated as you move the mouse.
<a href="javascript:void(0);">Test 1</a> <a href="javascript:void(0);">Test 2</a> <script type="text/javascript"> var msg = "Hello, world!"; $(function() { $("a").bind("click", { message : msg }, function(event) { msg = "Changed msg"; alert(event.data.message); }); }); </script>We pass the value as the secondary parameter of the bind() method, as a map of keys and values. You can pass more than one value by separating them with a comma. To access the value inside the event handler, we use the data property of the event object. This property contains sub-properties for each of the values you have passed, which means that you can access the value of the message parameter using event.data.message.
$("a").unbind();This will remove any event handlers that you have attached with the bind() function. However, you may want to only remove event subscriptions of a specific type, for instance clicks and doubleclicks:
$("a").unbind("click doubleclick");Simply separate the event types with a comma. Here is a more complete example, where you can see it all in effect:
<a href="javascript:void(0);">Test 1</a> <a href="javascript:void(0);">Test 2</a> <script type="text/javascript"> var msg = "Hello, world!"; $(function() { $("a").bind("click", function() { $("a").unbind("click"); alert("First and only message from me!"); }); }); </script>In this little example, we subscribe to the click event of all links. However, once a link is clicked, we remove all the subscriptions and alert the clicker about it. The event handler will no longer be activated by the links.
<a href="javascript:void(0);">Test 1</a> <a href="javascript:void(0);">Test 2</a> <script type="text/javascript"> var msg = "Hello, world!"; $(function() { $("a").bind("click", function() { alert("First event handler!"); }); $("a").bind("click", function() { alert("Second event handler!"); $("a").unbind("click"); }); }); </script>However, this opens up for the possibility that once you unbind an event, you may be removing event subscriptions used a whole other place in your code, which you still need. If you try the example, you will see the result of this - when you click a link, all of the event subscriptions are removed. jQuery allows you to specify a secondary argument, which contains a reference to the specific handler you would like to remove. This way, we can make sure that we only remove the event subscription we intend to. Here's an example:
<a href="javascript:void(0);">Test 1</a> <a href="javascript:void(0);">Test 2</a> <script type="text/javascript"> var msg = "Hello, world!"; $(function() { var handler1 = function() { alert("First event handler!"); } var handler2 = function() { alert("Second event handler!"); $("a").unbind("click", handler2); } $("a").bind("click", handler1); $("a").bind("click", handler2); }); </script>By specifying handler2 as the secondary parameter, only this specific event handler is removed. Try the example. The secondary message is only displayed the first time you click the link.
<div id="divTestArea1"> <a href="javascript:void(0);" onclick="AddBox();">Add box</a> <div class="test">This is a box</div> </div> <script type="text/javascript"> $(function() { $(".test").bind("mouseover", function() { $(this).css("background-color", "blue"); }).bind("mouseout", function() { $(this).css("background-color", "white"); }); }); function AddBox() { var div = $("<div></div>").addClass("test").text("Another box"); $("#divTestArea1").append(div); } </script>Okay, this example might seem a bit complicated, but actually it's not. Let me walk you through it. We have a link, which will call the AddBox() JavaScript method, and then we have a div with the class "test". The AddBox() method will simply add another div to the page, with the same class, so that when you click the link, you get yet another box on the page. In the ready event, we select all elements with the "test" class and then we bind a handler to two of the events: The mouseover and the mouseout event, where we change the color of the element invoking the event. Try the example in your browser. The first div will have the mouseover effect, but if you click the link to add more boxes, they won't have the same effect. The reason is pretty obvious: We attached the events before these new boxes were created.
<div id="divTestArea2"> <a href="javascript:void(0);" onclick="AddBox();">Add box</a> <div class="test">This is a box</div> </div> <script type="text/javascript"> $(function() { $(".test").live("mouseover", function() { $(this).css("background-color", "blue"); }).live("mouseout", function() { $(this).css("background-color", "white"); }); }); function AddBox() { var div = $("<div></div>").addClass("test").text("Another box"); $("#divTestArea2").append(div); } </script>Now if you run this example, you will see that even though you add new elements after the page has loaded, jQuery will automatically attach the event handlers to them for you. The live() method works just like bind() in all the other aspects, so check the previous chapters for more information on it. The same goes for the die() method, which works just like the unbind() method, but should be used for cases where the live() method has been used.
<div id="divContent"> <b>This is external content</b> </div> And there's more of itSave it as content.html, in the same directory where you keep your other example files for this tutorial. We can load it as simple as this:
<div id="divTestArea1"></div> <script type="text/javascript"> $(function() { $("#divTestArea1").load("content.html"); }); </script>If you have the content file in another directory, or if you have named it differently, you will have to change the parameter for the load method accordingly. This is all it takes to load content from an external file with jQuery and the load method. A pretty cool trick is that you can actually pass a selector along with the URL, to only get a part of the page. In the first example, we loaded the entire file, but in the following example, we will only use the div, which contains the first sentence:
<div id="divTestArea2"></div> <script type="text/javascript"> $(function() { $("#divTestArea2").load("content.html #divContent"); }); </script>As you can see, we simply append a standard jQuery selector to the parameter, after the URL, separated with a space. This causes jQuery to select the content out and only pass the matched part(s) back to the container. You can use any jQuery selector type to pull off this trick, which makes it pretty powerful.
<div id="divTestArea3"></div> <script type="text/javascript"> $(function() { $("#divTestArea3").load("no-content.html", function(responseText, statusText, xhr) { if(statusText == "success") alert("Successfully loaded the content!"); if(statusText == "error") alert("An error occurred: " + xhr.status + " - " + xhr.statusText); }); }); </script>As you can see, the callback function specifies 3 parameters, which jQuery will fill in for you. The first parameter will contain the resulting content if the call succeeds. The second parameter is a string which specifies the status of the call, e.g. "success" or "error". You can use it to see if the call was successful or not. The third parameter is the XMLHttpRequest object used to perform the AJAX call. It will contain properties which you can use to see what went wrong and many other things.
<script type="text/javascript"> $(function() { $.get("content.html", function(data, textStatus) { alert("Done, with the following status: " + textStatus + ". Here is the response: " + data); }); }); </script>The first parameter is the URL, which is just content.html. The second parameter is more interesting. It's a callback function, which jQuery calls if the page request succeeds. The first callback parameter is simply the content of the page requested, while the second callback parameter is the textual status of the request.
<script type="text/javascript"> $(function() { $.post("test_post.php", { name: "John Doe", age: "42" }, function(data, textStatus) { alert("Response from server: " + data); }); }); </script>This example is much like the first one, but we make the POST request to another page, in this example a PHP page, and as the second parameter, we pass in a map of POST parameters. The map is constructed of two parameters, a name and an age. If we had used a GET request instead of a POST request (POST requests doesn't take parameters from the URL like GET does), the above code would actually have corresponded to requesting an URL like this in your browser:
<?php $users = array ( array("name" => "John Doe", "age" => 42), array("name" => "Jane Doe", "age" => 39) ); echo $_REQUEST['callback'] . "(" . json_encode($users) . ")"; ?>To see what data returned looks like, try opening the following URL in your browser:
<ul id="ulUsers"></ul> <script type="text/javascript"> $(function() { $.get ( "http://tests.jquery-tutorial.net/json.php?callback=?", function(data, textStatus) { $.each(data, function(index, user) { $("#ulUsers").append($("<li></li>").text(user.name + " is " + user.age + " years old")); }); }, "json" ); }); </script>If you read the chapter on the get() and post() methods, you will see that there are only two main differences: The callback parameter on the URL, and the extra parameter specifying that we want the return type to be "json". The callback is set to a question mark, which will make jQuery generate a random one for us. In the script that takes the call, the value of this parameter is used, as you can see in the PHP code above.
<input type="button" name="btnDoRequest" value="Perform calculation" onclick="PerformCalculation(this);" /> <script type="text/javascript"> function PerformCalculation(sender) { $(sender).val("Working - please wait..."); $.get("/tests/calc.php", function(data, textStatus) { $(sender).val("Perform calculation"); alert(data); }); } </script>Right before performing the AJAX request, we change the text of the sender (the button which calls the function). As soon as it succeeds, we set it back. That's the simplest form of progress. Another approach is to show a piece of text somewhere on the page, but the most common way of doing it is to show a little piece of graphic which illustrates that the browser is currently working. You could make one yourself, or even better: Use one of the great online generators, for instance http://ajaxload.info/. I've created one, as you can see in the next example:
<input type="button" name="btnDoRequest" value="Perform calculation" onclick="PerformCalculationWithImageProgress();" /> <img src="/images/ajax-loader.gif" style="display: none;" id="imgProgress" /> <script type="text/javascript"> function PerformCalculationWithImageProgress() { $("#imgProgress").show(); $.get("/tests/calc.php", function(data, textStatus) { $("#imgProgress").hide(); alert(data); }); } </script>The process is pretty much the same, but instead of setting a text, we show and hide an existing image. You can place the image in a spot that the user is most likely to notice or dynamically place the image next to button/link clicked, if you have more than one. The possibilities are really endless.
<input type="button" name="btnDoRequest" value="Perform calculation" onclick="PerformCalculationWithErrorHandling(this);" /> <script type="text/javascript"> function PerformCalculationWithErrorHandling(sender) { $(sender).val("Working - please wait..."); $.get("/tests/non-existing.php", function(data, textStatus) { $(sender).val("Perform calculation"); alert(data); }).error(function() { $(sender).val("Try again"); alert("An error occurred.") }); } </script>It's pretty much identical to the first example, but here we call the error function on the returned AJAX object and pass in a callback function which should be called if the request fails, which it will in this example, since I have changed the path for the requested file to something which doesn't exist.
<input type="button" name="btnDoRequest" value="Start" onclick="PerformSimpleCalculation();" /> <script type="text/javascript"> function PerformSimpleCalculation() { $.get("/tests/calc.php", function(data, textStatus) { alert(data); }); } </script>It requests a PHP script which is doing a very complicated calculation (as you will see from the result), which means that it usually takes ~3 seconds to finish. Now, try the example and push the button several times after each other. The same "calculation" will be performed multiple times and the result will also be displayed multiple times (with a 3 second delay).
<input type="button" name="btnDoRequest" value="Start" onclick="PerformAbortableCalculation();" /> <script type="text/javascript"> var calculationRequest = null; function PerformAbortableCalculation() { if(calculationRequest != null) calculationRequest.abort(); calculationRequest = $.get("/tests/calc.php", function(data, textStatus) { alert(data); }); } </script>We start off by defining a common variable for containing the request reference. In the PerformAbortableCalculation() method, we assign the return value of the get() call to this variable, but before we do so, we check to see if it's null (the method hasn't been used yet) and if not, we call the abort() method on it. If you try this example and click several times, you will see that no matter how many times you click the button, it only executes the callback function once.
<a href="javascript:void(0);" onclick="ShowElementDimensions();">Show element dimensions</a> <div id="divTestArea1" style="height: 100px; width: 400px; padding: 20px; margin: 3px; border: 1px solid silver; background-color: #eee;"></div> <script type="text/javascript"> function ShowElementDimensions() { var result = ""; result += "Dimensions of div: " + $("#divTestArea1").width() + "x" + $("#divTestArea1").height() + "</br>"; result += "Inner dimensions of div: " + $("#divTestArea1").innerWidth() + "x" + $("#divTestArea1").innerHeight() + "</br>"; result += "Outer dimensions of div: " + $("#divTestArea1").outerWidth() + "x" + $("#divTestArea1").outerHeight() + "</br>"; result += "Outer dimensions of div (with margin): " + $("#divTestArea1").outerWidth(true) + "x" + $("#divTestArea1").outerHeight(true) + "</br>"; $("#divTestArea1").html(result); } </script>The example is quite simple. We have a div element with extra padding, extra margin and a border. When we click the link, we use the width()/height(), innerWidth()/innerHeight() and outerWidth()/outerHeight() methods to show the dimensions of the element.
<a href="javascript:void(0);" onclick="ShowBrowserDimensions();">Show browser dimensions</a> <script type="text/javascript"> function ShowBrowserDimensions() { alert("Dimensions of document: " + $(document).width() + "x" + $(document).height()); alert("Dimensions of window: " + $(window).width() + "x" + $(window).height()); } </script>We check the width and height for both the document (the HTML document) and the window (the browser viewport), since these may or may not differ.
<a href="javascript:void(0);" onclick="ResizeElement();">Resize element</a> <div id="divTestArea3" style="height: 100px; width: 300px; padding: 20px; border: 1px solid silver; background-color: #eee;"> <script type="text/javascript"> function ResizeElement() { $("#divTestArea3").width(150).height(50); } </script>
<div id="divTestArea1"></div> <script type="text/javascript"> $.noConflict(); jQuery("#divTestArea1").text("jQuery is still here!"); </script>If you think that "jQuery" is too much to type each time, you can create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in your own little variable, for later use. Here's how it looks:
<div id="divTestArea2"></div> <script type="text/javascript"> var jQ = $.noConflict(); jQ("#divTestArea2").text("jQuery is still here!"); </script>If you have a block of jQuery code which uses the $ shortcut and you don't feel like changing it all, you can use the following construct. It's yet another version of the ready method, where $ is passed in as a parameter. This allows you to access jQuery using $, but only inside of this function - outside of it, other frameworks will have access to $ and you will have to use "jQuery":
<div id="divTestArea3"></div> <script type="text/javascript"> $.noConflict(); jQuery(document).ready(function($) { $("#divTestArea3").text("jQuery is still here!"); }); </script>